package com.alex.common.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alex.common.Constants;
import com.alex.common.ILogger;

public abstract class URLFetchUtils {

	public static StringBuilder buildQStr(String qStr, EncodeEnum reqEncode)
			throws UnsupportedEncodingException {
		if (qStr.indexOf(" ") != 0) {
			String[] strs = qStr.split(" ");
			StringBuilder sb = new StringBuilder(URLEncoder.encode(strs[0],
					reqEncode.toString()));
			for (int i = 1; i < strs.length; i++) {
				sb.append("+").append(
						URLEncoder.encode(strs[i], reqEncode.toString()));
			}
			return sb;
		} else if (qStr.indexOf("+") != 0) {
			String[] strs = qStr.split("/+");
			StringBuilder sb = new StringBuilder(URLEncoder.encode(strs[0],
					reqEncode.toString()));
			for (int i = 1; i < strs.length; i++) {
				sb.append("+").append(
						URLEncoder.encode(strs[i], reqEncode.toString()));
			}
			return sb;
		} else {
			return new StringBuilder(URLEncoder.encode(qStr,
					reqEncode.toString()));
		}
	}

	private final static String UserAgent = "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)";

	/**
	 * 
	 * @param hostAddr
	 * @param uri
	 * @param resEncode
	 * @return
	 * @throws IOException
	 */
	static String fetchContentByURLStream(String hostAddr, String uri,
			EncodeEnum resEncode) throws IOException {
		BufferedReader bfReader = null;
		InputStreamReader inReader = null;
		try {
			URLConnection conn = new URL(hostAddr + uri).openConnection();
			conn.setRequestProperty("User-Agent", UserAgent);
			inReader = new InputStreamReader(conn.getInputStream(),
					resEncode.toString());
			bfReader = new BufferedReader(inReader,
					Constants.URL_FETCH_READ_BUFFER_SIZE);
			StringBuilder sb = new StringBuilder(
					Constants.URL_FETCH_READ_BUFFER_SIZE);
			String line;
			while ((line = bfReader.readLine()) != null) {
				sb.append(line).append("\n");
			}
			return sb.toString();
		} catch (Exception e) {
			ILogger.logger_common.error(e.getMessage(), e);
			throw new RuntimeException(e);
		} finally {
			if (bfReader != null)
				bfReader.close();
			if (inReader != null)
				inReader.close();
		}
	}

	static Pair<String, String> getHostPort(String hostAddr) {
		Pattern pattern = Pattern
				.compile("http[\\w]*://([\\w|.|-]+)(:([\\d]+))*");
		Matcher matcher = pattern.matcher(hostAddr);
		matcher.find();
		return new Pair<String, String>(matcher.group(1), matcher.group(3));
	}

	/**
	 * 程序写的有问题
	 * 
	 * @param host
	 * @param uri
	 * @return
	 * @throws IOException
	 * 
	 */
	@Deprecated
	static String fetchContentByHttpClient(String hostAddr, String uri,
			EncodeEnum resEncode) throws IOException {
		// HttpClient client = new HttpClient();
		// Pair<String, String> hostport = getHostPort(hostAddr);
		// if (hostport.snd == null) {
		// client.getHostConfiguration().setHost(hostport.fst);
		// } else {
		// client.getHostConfiguration().setHost(hostport.fst,
		// Integer.parseInt(hostport.snd));
		// }
		// 不使用代理
		// if (false) {
		// String proxyuri = "127.0.0.1";
		// client.getHostConfiguration().setProxy(proxyuri, 80);
		// }
		// 不使用Post
		// PostMethod post = new PostMethod(url);
		// post.setRequestHeader("Content-type", "text/html;
		// charset=ISO-8859-1");
		// 使用Get
		// GetMethod get = new GetMethod(uri);
		// get.setRequestHeader("Content-type", "text/html; charset=GBK");
		// //int status = client.executeMethod(get);
		// if (status != 200) {
		// throw new IOException("Http client output status is not correct. "
		// + status);
		// }
		// BufferedReader reader = new BufferedReader(new InputStreamReader(
		// get.getResponseBodyAsStream(), resEncode.toString()));

		StringBuilder sb = new StringBuilder(750);
		// String line;
		// while ((line = reader.readLine()) != null) {
		// sb.append(line);
		// }
		// reader.close();
		return sb.toString();
	}
}
